package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnLikeBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnLikeBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUnLikeBehaviorServiceImpl extends ServiceImpl<ApUnLikeBehaviorMapper, ApUnlikesBehavior> implements ApUnLikeBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //检查参数
        if (dto == null || dto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (user.getId() == null && dto.getEquipmentId() != 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询不喜欢行为
        ApUnlikesBehavior apUnlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
        //判断参数保存不喜欢行为或取消不喜欢行为
        if (apUnlikesBehavior == null&&dto.getType().equals((short)0)) {
            apUnlikesBehavior= new ApUnlikesBehavior();
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setType(dto.getType());
            apUnlikesBehavior.setCreatedTime(new Date());
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            save(apUnlikesBehavior);
        }else {
            apUnlikesBehavior.setCreatedTime(new Date());
            apUnlikesBehavior.setType(dto.getType());
            updateById(apUnlikesBehavior);
        }
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
